package cn.leedsoft.and.crimeintent.controller.photo_gallery;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.*;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.*;
import android.widget.*;
import cn.leedsoft.and.crimeintent.R;
import cn.leedsoft.and.crimeintent.model.photo_gallery.GalleryItem;
import cn.leedsoft.and.crimeintent.model.photo_gallery.PhotoHttpFetcher;
import cn.leedsoft.and.crimeintent.model.photo_gallery.PicDownloader;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * Created by leeds on 2016/8/23 23:12.
 */
public class PhotoGalleryFragment extends ListFragment {
    private static final String TAG = PhotoGalleryFragment.class.getSimpleName();
    private ListView mListView;
    private PhotoHttpFetcher mPhotoFetcher = new PhotoHttpFetcher();
    private List<GalleryItem> mGalleryItems = Lists.newArrayList();
    private PicDownloader<ImageView> mPicDownloader;//handler thread 长时间、重复的任务
    private static final int PRELOAD_RADIUS = 3;
    private SharedPreferences mSharedPreferences;
    private SearchView mSearchView;
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getActivity(), "Got a broadcast intent : " + intent.getAction(), Toast.LENGTH_SHORT).show();
            mBroadcastReceiver.setResultCode(Activity.RESULT_CANCELED);//取消通知信息
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter(PollService.ACTION_SHOW_NOTIFICATION);
        getActivity().registerReceiver(mBroadcastReceiver, intentFilter, PollService.CUSTOM_PRIVATE, null);// dynamic register broadcast receiver
    }

    @Override
    public void onPause() {
        super.onPause();
        getActivity().unregisterReceiver(mBroadcastReceiver);//unregister
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_VIEW);//隐式intent 调用系统浏览器
        intent.setClass(getActivity(), PhotoPageActivity.class);
        Uri pageUrl = Uri.parse(mGalleryItems.get(position).getPageUrl());
        intent.setData(pageUrl);
        startActivity(intent);
    }

    public static PhotoGalleryFragment newInstance() {
        Bundle args = new Bundle();

        PhotoGalleryFragment fragment = new PhotoGalleryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        setHasOptionsMenu(true);

        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        new FetchItemTask().execute();//AsyncTask 主要应用于那些短暂且较少重复的任务。。
        //它使用一个Executor在单一的后台线程上运行所有AsyncTask的后台任务。这意味着每个AsyncTask都需要排队逐个运行。显然，长时间运行的AsyncTask会阻塞其他AsyncTask

        mPicDownloader = new PicDownloader<ImageView>(new Handler(), new PicDownloader.Listener<ImageView>() {
            @Override
            public void onPicDownloaded(ImageView imageView, Bitmap bitmap, GalleryItem item) {
                if (bitmap == null) {
                    ((ArrayAdapter<GalleryItem>) getListAdapter()).remove(item);
                    return;
                }
                if (isVisible()) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        });
        mPicDownloader.start();
        mPicDownloader.getLooper();//init looper
        Log.i(TAG, "background thread started!");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPicDownloader.quit();
        Log.i(TAG, "background thread destroyed!");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mListView = (ListView) view.findViewById(android.R.id.list);
        return view;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupAdapter(List<GalleryItem> appendItems) {
        if (getActivity() == null || mListView == null) return;
        if (getListAdapter() == null) {
            mGalleryItems.addAll(appendItems);
            setListAdapter(new GalleryAdapter(mGalleryItems));
        } else {
            ((ArrayAdapter<GalleryItem>) getListAdapter()).addAll(appendItems);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.photo_search, menu);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {//ActionBarActivity中，应使用app:actionViewClass ，而非android:actionViewClass
            MenuItem menuItem = menu.findItem(R.id.menu_item_search);
            mSearchView = (SearchView) menuItem.getActionView();
            mSearchView.setSubmitButtonEnabled(true);
            mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    Toast.makeText(getActivity(), "您搜索的是：" + query, Toast.LENGTH_SHORT).show();
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });

            SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
            SearchableInfo searchableInfo = searchManager.getSearchableInfo(getActivity().getComponentName());
            Log.d(TAG, "activity's componentName is :" + getActivity().getComponentName());

            mSearchView.setSearchableInfo(searchableInfo);
        }
    }

    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
//            case R.id.menu_item_search:
//                getActivity().onSearchRequested();
//                return true;
            case R.id.menu_clear_search:
                if (mSharedPreferences.getString("_nihao", null) == null) {
                    mSharedPreferences.edit().putString("_nihao", "你好！！！preference！").commit();
                    Toast.makeText(getActivity(), "【_nihao】是空的。成功存储数据", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), mSharedPreferences.getString("_nihao", null), Toast.LENGTH_SHORT).show();
                    mSharedPreferences.edit().remove("_nihao").commit();
                }
                return true;
//            case R.id.menu_do_search:
//                Intent intent = new Intent(getActivity(), PhotoGalleryActivity.class);
//                intent.setAction(Intent.ACTION_SEARCH);
//                intent.putExtra(SearchManager.QUERY, mSearchView.getQuery().toString());
//                startActivity(intent);
//                return true;
            case R.id.menu_photo_ss_alarm:
                boolean toOpen = !PollService.isAlarmOn(getActivity());
                PollService.setAlarmService(getActivity(), toOpen);

//                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//                    getActivity().invalidateOptionsMenu();
//                }

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        MenuItem menuItem = menu.findItem(R.id.menu_photo_ss_alarm);
        if(PollService.isAlarmOn(getActivity())) {
            menuItem.setTitle(R.string.photo_stop_alarm);
        } else {
            menuItem.setTitle(R.string.photo_start_alarm);
        }
    }

    private class FetchItemTask extends AsyncTask<Integer, Void, List<GalleryItem>> {
        @Override
        protected List<GalleryItem> doInBackground(Integer... params) {
            List<GalleryItem> itemList = mPhotoFetcher.fetch();
            Log.i(TAG, "fetched pictures :" + itemList.size());
            return itemList;
        }

        @Override
        protected void onPostExecute(List<GalleryItem> galleryItems) {
            setupAdapter(galleryItems);
        }
    }

    private class GalleryAdapter extends ArrayAdapter<GalleryItem> {
        public GalleryAdapter(List<GalleryItem> items) {
            super(getActivity(), 0, items);
            setNotifyOnChange(false);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.i(TAG, "show list view : " + position);

            if (position == getCount() - 4) {//滑动到倒数第三个 加载更多
                new FetchItemTask().execute();
            }

            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.photo_gallery_item, parent, false);
            }
            ImageView imageView = (ImageView) convertView.findViewById(R.id.photo_imageview_item);
            imageView.setImageResource(R.mipmap.loading_cat);

            GalleryItem item = mGalleryItems.get(position);
            mPicDownloader.queuePic(imageView, item, genPreloadUrls(position));
            return convertView;
        }

        private List<String> genPreloadUrls(int position) {
            List<String> res = Lists.newArrayList();
            for (int i = 1; i <= PRELOAD_RADIUS; i++) {
                if (position - i >= 0) {
                    res.add(getItem(position - i).getUri());
                }
                if (position + i <= getCount() - 1) {
                    res.add(getItem(position + i).getUri());
                }
            }
            return res;
        }
    }
}
